package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1、校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码格式不正确");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //将验证码保存到session
        //session.setAttribute("code",code);
        //保存到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.debug("验证码发送成功，{}",code);
        return Result.ok();
    }

    @Override
    public Result loginAndRegister(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1、再次校验手机号码，防止前后手机号码不一致
        if(RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号码格式不正确");
        }
        //用户输入的验证码
        String code = loginForm.getCode();
        //2、校验验证码是否一致，这里的验证码是用输入进session的
        String checkCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if(!code.equals(checkCode)){
            return Result.fail("验证码不正确");
        }
        //3、查询数据库是否有该用户手机号
        User user = query().eq("phone", phone).one();
        //4、如果没有者完成注册
        if(user == null){
            user = createByPhone(phone);
        }
        //有的话，将用户信息保存到token里面
        String token = UUID.randomUUID().toString(true);
         //5有的话，将用户信息保存到session里面
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将userDTO的属性包装到Map
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userDTO
                ,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).
                        setFieldValueEditor((filedName,filedValue)->filedValue.toString()));
        //再存入redis
        String loginUser = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(loginUser,stringObjectMap
       );
        //设置失效时间
        stringRedisTemplate.expire(loginUser,LOGIN_USER_TTL,TimeUnit.MINUTES);
        System.out.println("token = " + token);
        //完成登入
        return Result.ok(token);
    }

    /**
     * 注册用户
     */
    public User createByPhone(String phone){
        User user = new User();
        user.setPhone(phone);
        //随机生成昵称
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX
                + RandomUtil.randomString(6));
        //保存用户
        save(user);
        return user;
    }
}
